//
//  UploadImagesView.m
//  Elife
//
//  Created by 拓客营 on 2022/4/16.
//

#import "UploadImagesView.h"
#import "UploadImgCollectionViewCell.h"

@implementation ChoseImagesModel

@end

@interface UploadImagesView ()<UICollectionViewDelegate, UICollectionViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate, TZImagePickerControllerDelegate>

@property (nonatomic, assign) NSInteger maxCount;
@property (nonatomic, assign) CGSize size;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray<TZAssetModel *> *selectedModels;
@property (nonatomic, retain) NSMutableArray *imgArr;
//@property (nonatomic, strong) NSMutableArray<UIImage *> *takePhotoArr;// 拍照选的图片
@end

@implementation UploadImagesView

-(instancetype)initWithFrame:(CGRect)frame itemSize:(CGSize)size withMax:(NSInteger)maxCount {
    if (self  = [self initWithFrame:frame]) {
        self.maxCount = maxCount;
        self.size = size;
        [self UIConfig];
        
    }
    return self;
}

-(void)UIConfig {
    
    [self addSubview:self.collectionView];
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
        make.height.mas_equalTo(self);
    }];
    
}
#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource
//分区，组
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {

    return 1;
}

//每一分区的单元个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    
    NSInteger count = 0;
    if (self.isEdit) {
        count = self.imgUrlsArr.count + self.imgArr.count;// 编辑，内有图片
    }else {
        count = self.imgArr.count;// 直接设置
    }
    
    
    if (count == 0) {
        return 1;
    }else {
        if (count == self.maxCount) {
            return self.maxCount;
        }
        return count + 1;
    }
}

//集合视图单元格大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return self.size;
}


//单元格复用
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UploadImgCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:UploadImgCollectionViewCellID forIndexPath:indexPath];
    
    
    if (self.isEdit) {
        NSInteger count = self.imgUrlsArr.count + self.imgArr.count;
        
        if (indexPath.row == count) {
            cell.img = ImageWithName(self.placeholderImgName ? self.placeholderImgName : @"icon_upload_img");
            cell.hidDeleteBtn = YES;
        }else {
            if (indexPath.row < self.imgUrlsArr.count) {
                cell.imgUrl = self.imgUrlsArr[indexPath.row];
                [self addCellBlockDeleteImgUrl:cell];
            }else {
                cell.img = self.imgArr[indexPath.row - self.imgUrlsArr.count];
                cell.assetModel = self.pickerController.selectedModels[indexPath.row - self.imgUrlsArr.count];
                [self addCellBlock:cell];
            }
            
            cell.hidDeleteBtn = NO;
        }
        return cell;
    }
    
    if (indexPath.row == self.imgArr.count) {
        // 添加图片
        cell.img = ImageWithName(self.placeholderImgName ? self.placeholderImgName : @"icon_upload_img");
        cell.hidDeleteBtn = YES;
    }else {
        // 照片获取到的照片
        cell.img = self.imgArr[indexPath.row];
        cell.assetModel = self.pickerController.selectedModels[indexPath.row];
        cell.hidDeleteBtn = NO;
    }
    [self addCellBlock:cell];
    return cell;
}

-(void)addCellBlock:(UploadImgCollectionViewCell *)cell {
    WeakSelf
    
    cell.deleteImgBlock = ^(UIImage * _Nonnull img) {
        if ([weakSelf.imgArr containsObject:img]) {
            [weakSelf.imgArr removeObject:img];
            [weakSelf.collectionView reloadData];
        }
    };
    
    cell.deleteAssetModelBlock = ^(TZAssetModel * _Nonnull model) {
        model.isSelected = NO;
        [weakSelf.pickerController removeSelectedModel:model];
    };
}

-(void)addCellBlockDeleteImgUrl:(UploadImgCollectionViewCell *)cell {
    WeakSelf
    cell.deleteImgUrlBlock = ^(NSString * _Nonnull imgUrl) {
        [weakSelf.imgUrlsArr removeObject:imgUrl];
        [weakSelf.collectionView reloadData];
    };
}

//被选中的单元格
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isEdit) {
        // 编辑
        NSInteger count = self.imgUrlsArr.count + self.imgArr.count;
        if (indexPath.row == count) {
            // 点击添加照片
//            [self openAlertControlller];
            [self openAlbum];
            
        }else {
            // 点击看大图
            if (indexPath.row < self.imgUrlsArr.count) {
                [CheckBigImgView imageWithURL:self.imgUrlsArr[indexPath.row]];
            }else {
                [CheckBigImgView imageWithImage:self.imgArr[indexPath.row - self.imgUrlsArr.count]];
            }
        }
        
        return;
    }
    
    if (indexPath.row == self.imgArr.count) {
        // 点击添加照片
//        [self openAlertControlller];
        [self openAlbum];
        
    }else {
        // 点击看大图
        [CheckBigImgView imageWithImage:self.imgArr[indexPath.row]];
    }
}

#pragma mark - photo
/*--------------------------------------Photo-----------------------------------------*/

//MARK: Photo

- (void)openAlertControlller {
    
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"选择照片方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];

    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self openCamera];
    }];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self openAlbum];
    }];

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL];

    [controller addAction:cameraAction];
    [controller addAction:albumAction];
    [controller addAction:cancelAction];

    [self yt_presentViewController:controller animated:YES completion:nil];

    
}

- (void)openCamera{
    
    if (![PrivacyRightsCheck detectionCameraState]) {
        return;
    }
    
    if (![PrivacyRightsCheck detectionPhotoState]) {
        return;
    }
    
    [self presentImagePickerControllerWithDelegator:self];
}

- (void)openAlbum{
    
//    if (![PrivacyRightsCheck detectionPhotoState]) {
//        return;
//    }
    
    WeakSelf
    NSInteger count = self.isEdit ? self.maxCount-self.imgUrlsArr.count : self.maxCount;
    [self presentAlbumControllerWithDelegate:self max:count callback:^(NSArray<UIImage *> * _Nonnull photos) {
        weakSelf.imgArr = photos.mutableCopy;
        weakSelf.selectedModels = weakSelf.pickerController.selectedModels.mutableCopy;
        [weakSelf.collectionView reloadData];
        
        ChoseImagesModel *model = [ChoseImagesModel new];
        model.imgArr = weakSelf.imgArr;
        model.imgUrlsArr = weakSelf.imgUrlsArr;
        weakSelf.imageModel = model;
    } clipSize:self.clipsSize];
    
}



//选择照片的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {

    UIImage* image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
//    [self.takePhotoArr addObject:image];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
        
}


//取消选择
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}
/*--------------------------------------Photo-----------------------------------------*/

#pragma mark - Set get
-(void)setImgUrlsArr:(NSMutableArray *)imgUrlsArr {
    _imgUrlsArr = imgUrlsArr;
    
    ChoseImagesModel *model = [ChoseImagesModel new];
    model.imgUrlsArr = imgUrlsArr;
    self.imageModel = model;
    
    [self.collectionView reloadData];
}

#pragma mark - lazy
-(UICollectionView *)collectionView {
    if (!_collectionView) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.minimumLineSpacing = 10;// 列间距
        layout.minimumInteritemSpacing = 0;
        layout.sectionInset = UIEdgeInsetsZero;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = UIColor.whiteColor;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[UploadImgCollectionViewCell class] forCellWithReuseIdentifier:UploadImgCollectionViewCellID];
//        _collectionView.backgroundColor = [UIColor orangeColor];
        _collectionView.clipsToBounds = YES;
    }
    return _collectionView;
}

-(NSMutableArray *)imgArr {
    if (!_imgArr) {
        _imgArr = [NSMutableArray new];
    }
    return _imgArr;
}

//-(NSMutableArray<UIImage *> *)takePhotoArr {
//    if (!_takePhotoArr) {
//        _takePhotoArr = [NSMutableArray new];
//    }
//    return _takePhotoArr;
//}
@end
